﻿using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using AzureDiagMon.Common;
using AzureDiagMon.Common.DataVirtualization;
using AzureDiagMon.Common.Dtos;
using AzureDiagMon.Common.Interfaces.Services;
using AzureDiagMon.ViewModels.Entities;
using Ninject;

namespace AzureDiagMon.ViewModels
{
    public class LogEntryItemsProvider : IItemsProvider<WadLogEntryRowViewModel>
    {
        private readonly StorageAccountDto storageAccount;
        private readonly EventFilter filter;
        private readonly bool isLocalTimeMode;
        private readonly IQueryable<WadLogEntryDto> query;

        [Inject]
        public IDataStoreService DataStore { get; set; }

        public LogEntryItemsProvider()
        {
            IoC.Inject(this);
        }

        public LogEntryItemsProvider(StorageAccountDto storageAccount, EventFilter filter, bool isLocalTimeMode)
            : this()
        {
            this.storageAccount = storageAccount;
            this.filter = filter;
            this.isLocalTimeMode = isLocalTimeMode;
            query = DataStore.GetLogEntries(storageAccount, filter);
        }

        public int FetchCount()
        {
            return query.Count();
            //return DataStore.GetLogEntryCount(storageAccount, filter);
        }

        public IList<WadLogEntryRowViewModel> FetchRange(int startIndex, int count)
        {
            //            return DataStore.ListLogEntries(storageAccount, filter, startIndex, count)
            lock (query)
            {
                return query.Skip(startIndex).Take(count)
                    .Select(f => new WadLogEntryRowViewModel(f, isLocalTimeMode))
                    .ToList();
            }
        }

        #region Implementation of INotifyCollectionChanged

        public event NotifyCollectionChangedEventHandler CollectionChanged;

        #endregion

        public void RaiseCollectionChanged()
        {
            if (CollectionChanged != null)
                CollectionChanged.Invoke(null, null);
        }
    }
}
